import Pyro.core
import Pyro.naming

import os
import sys

from pojo import *

from multiprocessing import Queue,Process

class BasicService(Pyro.core.ObjBase, Process):
    def __init__(self, debug = False):
        Process.__init__(self)
        Pyro.core.ObjBase.__init__(self)
        self.debug = debug
	self.result_set = []
        self.request_queue = Queue()
        self.result_queue = Queue()
 
    def set_ppid(self, pid):
        self.daemon_pid = pid

    def run(self):
	while True:
            command, args = self.request_queue.get()
            if self.debug:
                print "command , args", (command, args)
            if command == "quit":
                print "shutdown..."
                self.result_queue.put("null")
                break
            if command == "ping":
                print "Ping received..."
                self.result_queue.put(True)
                continue
            self.result_queue.put(self.process_command(command,args))
        print "About to kill pid", self.daemon_pid
        os.kill(self.daemon_pid, 9)

    def process_command(self, command, args):
        pass

    def stop(self):
        return self.execute("quit",())

    def ping(self):
        return self.execute("ping",())

    def result(self, to_return):
        self.result_queue.put(to_return)
     
    def execute(self, command, args , block = True):
	self.request_queue.put((command,args))
        if not block:
            return None
	return self.result_queue.get(block)

def resolve_service(service_name):
    service_path = "PYRONAME://{0}".format(service_name)
    return Pyro.core.getProxyForURI(service_path)


def launch_service(service, service_name):
    Pyro.config.PYRO_TRACELEVEL = 3
    Pyro.config.PYRO_LOGFILE='log_file'
    Pyro.config.PYRO_MAXCONNECTIONS = 10

    Pyro.core.initServer()
    locator = Pyro.naming.NameServerLocator()
    ns = locator.getNS()
    daemon = Pyro.core.Daemon()
    daemon.useNameServer(ns)

    service.set_ppid(os.getpid())
    daemon.connect(service, service_name)
    service.start()
	   
    try:
        daemon.requestLoop()
    except Exception , e:
        print str(e)
    finally:
	server.shutdown()
        daemon.shutdown(True)
	
